const path=require('path');
function InlineWebpackPlugin() {
	
}
InlineWebpackPlugin.prototype.apply=function (compiler) {
	let self=this;
	compiler.hooks.compilation.tap('compilation',function (compilation) {
		compilation.hooks.htmlWebpackPluginAlterAssetTags.tapAsync('InlineWebpackPlugin',function (htmlPluginData,callback) {
			if (!htmlPluginData.plugin.options.inlineSource) {
				return callback(null,htmlPluginData);
			}
			let regextStr=htmlPluginData.plugin.options.inlineSource;
			let result=self.processTags(compilation,regextStr,htmlPluginData);
			console.log(result);
			callback(null,result);
		});
	});
}
InlineWebpackPlugin.prototype.processTags=function (compilation,regextStr,htmlPluginData) {
	let self=this;
	let head=[];
	let body=[];
	let regex=new RegExp(regextStr);
	htmlPluginData.head.forEach(tag => head.push(self.processTag(compilation,regex,tag)));
	htmlPluginData.body.forEach(tag => body.push(self.processTag(compilation,regex,tag)));
	return {...htmlPluginData,head,body}
}

InlineWebpackPlugin.prototype.processTag=function (compilation,regex,tag) {
	console.log(tag);
	let assetUrl;
	if (tag.tagName == 'script' && regex.test(tag.attributes.src)) {
		assetUrl=tag.attributes.src;
		tag={
			tagName: 'script',
			closeTag: true,
			attributes: {
				type:'text/javascript'
			}
		}
	} else if(tag.tagName == 'link' && regex.test(tag.attributes.href)) {
		assetUrl=tag.atttributes.href;
		tag={
			tagName: 'style',
			closeTag: true,
			attributes: {
				type:'text/css'
			}
		}
	}
	if (assetUrl) {
		let asset=compilation.assets[assetUrl];
		tag.innerHTML=asset.source();
	}
	return tag;
}

module.exports=InlineWebpackPlugin;
//https://github.com/DustinJackson/html-webpack-inline-source-plugin
//https://github.com/jantimon/html-webpack-plugin